package com.leecode.xiehf.page_01;

/**
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * <p>
 * 你可以假设数组中无重复元素。
 * https://leetcode-cn.com/problems/search-insert-position/
 */
public class Solution_0035 {

    public static void main(String[] args) {
        Solution_0035 solution = new Solution_0035();
        int result = solution.searchInsert(
                new int[]{1, 3, 5, 6}
                , 0);
        System.out.println(result);
    }

    public int searchInsert(int[] nums, int target) {
        if (nums.length == 0) {
            return 0;
        }
        return getIndex(nums, 0, nums.length - 1, target);
    }

    private int getIndex(int[] nums, int left, int right, int target) {
        if (left == right) {
            if (nums[right] < target) {
                return right + 1;
            }
            if (nums[left] > target) {
                return left;
            }
        }
        int mid = (left + right) / 2;
        if (nums[mid] == target) {
            return mid;
        } else if (nums[mid] > target) {
            // 左边
            return getIndex(nums, left, mid, target);
        } else {
            // 右边
            return getIndex(nums, mid + 1, right, target);
        }
    }
}

